package com.vitaf.cash.app.utils.decoration

import android.content.Context
import android.graphics.Rect
import android.util.TypedValue
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ItemDecoration

/**
 * GridSpacingItemDecoration
 * @Author wwdeng
 * @CreateTime: 2024/10/17 14:46
 * @Annotation：GridLayoutManager（网格布局）设置item的间隔
 */
class GridSpacingItemDecoration private constructor(
    private val spanCount: Int,
    private val spacing: Int,
    private val includeEdge: Boolean,
    private val includeTop: Boolean,
    private val includeBottom: Boolean
) : ItemDecoration() {

    override fun getItemOffsets(
        outRect: Rect,
        view: View,
        parent: RecyclerView,
        state: RecyclerView.State
    ) {
        val position = parent.getChildAdapterPosition(view)
        if (position == RecyclerView.NO_POSITION) return

        val column = position % spanCount

        if (includeEdge) {
            outRect.left = spacing - column * spacing / spanCount
            outRect.right = (column + 1) * spacing / spanCount

            // 顶部间距
            if (includeTop && position < spanCount) {
                outRect.top = spacing
            }
            // 底部间距
            if (includeBottom) {
                outRect.bottom = spacing
            }
        } else {
            outRect.left = column * spacing / spanCount
            outRect.right = spacing - (column + 1) * spacing / spanCount

            // 顶部间距（从第二行开始）
            if (includeTop && position >= spanCount) {
                outRect.top = spacing
            }
        }
    }

    companion object {
        fun create(
            spanCount: Int,
            spacingDp: Int,
            context: Context,
            includeEdge: Boolean = true,
            includeTop: Boolean = true,
            includeBottom: Boolean = true
        ): GridSpacingItemDecoration {
            val spacingPx = dpToPx(spacingDp, context)
            return GridSpacingItemDecoration(spanCount, spacingPx, includeEdge, includeTop, includeBottom)
        }

        private fun dpToPx(dp: Int, context: Context): Int {
            return TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP,
                dp.toFloat(),
                context.resources.displayMetrics
            ).toInt()
        }
    }
}
